package com.pipi.sso.web.shiro;

import com.google.common.collect.Maps;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * All rights Reserved, Designed By www.maihaoche.com
 *
 * @Package com.pipi.oo.web.shiro
 * @date: 2019/3/19 7:11 PM
 * @Copyright: 2017-2020 www.maihaoche.com Inc. All rights reserved.
 */
@Configuration
public class ShiroConfiguration {

    /**
     * <p> 自定义身份认证 realm </p>
     * @param
     * @return MyShiroRealm
     * @throws
     * @date 2019/3/19 11:16 PM
     */
    @Bean
    public MyShiroRealm myShiroRealm() {
       return new MyShiroRealm();
    }

    /**
     * <p> 权限管理，配置主要是Realm的管理认证 </p>
     * @param
     * @return SecurityManager
     * @throws
     * @date 2019/3/19 11:16 PM
     */
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myShiroRealm());
        return securityManager;
    }

    /**
     * <p> Filter工厂，设置对应的过滤条件和跳转条件 </p>
     * @param securityManager
     * @return ShiroFilterFactoryBean
     * @throws
     * @date 2019/3/19 11:15 PM
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //登录
        shiroFilterFactoryBean.setLoginUrl("/toLogin.json");
        //首页
        shiroFilterFactoryBean.setSuccessUrl("/index.json");
        //错误页面，认证不通过跳转
        shiroFilterFactoryBean.setUnauthorizedUrl("/error");

        Map<String,String> map = Maps.newHashMap();
        //登出
        map.put("/logout.json","logout");
        //对所有用户认证
        map.put("/**","authc");
        // 释放静态资源
        map.put("/static/**","anon");
        // 释放登陆请求
        map.put("/login.json","anon");
        // 管理员权限
        map.put("/admin/**", "roles[admin]");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}